package com.gscitysfy.cus.drain.modules.resource.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gscitysfy.cus.drain.config.BusinessException;
import com.gscitysfy.cus.drain.modules.command.entity.DangerSituationManage;
import com.gscitysfy.cus.drain.modules.command.entity.InstructTeam;
import com.gscitysfy.cus.drain.modules.command.mapper.DangerSituationManageMapper;
import com.gscitysfy.cus.drain.modules.command.mapper.InstructTeamMapper;
import com.gscitysfy.cus.drain.modules.resource.convert.ResourceTeamConvert;
import com.gscitysfy.cus.drain.modules.resource.dto.ResourceTeamDto;
import com.gscitysfy.cus.drain.modules.resource.entity.ResourceTeam;
import com.gscitysfy.cus.drain.modules.resource.mapper.ResourceTeamMapper;
import com.gscitysfy.cus.drain.modules.resource.service.IResourceTeamService;
import com.gscitysfy.cus.drain.modules.resource.vo.ResourceTeamQuery;
import lombok.AllArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 防汛队伍表 服务实现类
 * </p>
 *
 * @author Administrator
 * @since 2022-10-23 16:30:26
 */
@AllArgsConstructor
@Service
public class ResourceTeamServiceImpl extends ServiceImpl<ResourceTeamMapper, ResourceTeam> implements IResourceTeamService {

    private final ResourceTeamConvert resourceTeamConvert;

    private final ResourceTeamMapper resourceTeamMapper;

    private final InstructTeamMapper instructTeamMapper;

    private final DangerSituationManageMapper dangerSituationManageMapper;

    @Override
    public IPage<ResourceTeamDto> fetchPage(Page page, ResourceTeamQuery query) {
        LambdaQueryWrapper<ResourceTeam> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper = buildQueryWrapper(queryWrapper, query);
        Page<ResourceTeam> resourceTeamPage = this.page(page, queryWrapper);
        return resourceTeamPage.convert(resourceTeamConvert::toDto);
    }

    @Override
    public List<ResourceTeamDto> list(Long dangerSituationId) {
        List<ResourceTeamDto> resourceTeamDtoList = new ArrayList<>();
        if (Objects.isNull(dangerSituationId)) {
            throw new BusinessException("缺少险情管理信息");
        }
        DangerSituationManage dangerSituationManage = dangerSituationManageMapper.selectById(dangerSituationId);
        LambdaQueryWrapper<ResourceTeam> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(ResourceTeam::getCmUsable, false);
        List<ResourceTeam> resourceTeamList = baseMapper.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(resourceTeamList)) {
            resourceTeamList.forEach(resourceTeam -> {
                resourceTeamDtoList.add(resourceTeamConvert.toDto(resourceTeam, dangerSituationManage));
            });
        }
        return resourceTeamDtoList;
    }

    @Override
    public ResourceTeamDto getById(Long cmKid) {
        ResourceTeam resourceTeam = baseMapper.selectById(cmKid);
        return resourceTeamConvert.toDto(resourceTeam);
    }

    @Override
    public List<ResourceTeamDto> fetchGis() {

        //未分配
        List<ResourceTeam> unAssignedResourceTeamList = resourceTeamMapper.fetchUnAssignedGis();
        unAssignedResourceTeamList.forEach(unAssignedResourceTeam -> {
            unAssignedResourceTeam.setAssignedFlag(false);
        });
        List<ResourceTeam> resourceTeamList = new ArrayList<>(unAssignedResourceTeamList);
        //已分配
        List<ResourceTeam> assignedResourceTeamList = resourceTeamMapper.fetchAssignedGis();
        assignedResourceTeamList.forEach(assignedResourceTeam -> {
            assignedResourceTeam.setAssignedFlag(true);
        });
        resourceTeamList.addAll(assignedResourceTeamList);
        return resourceTeamConvert.toDtoList(resourceTeamList);
    }

    @Override
    public List<ResourceTeamDto> fetchInIdList(List<Long> idList) {
        LambdaQueryWrapper<ResourceTeam> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.in(ResourceTeam::getCmKid, idList);
        List<ResourceTeam> resourceTeamList = baseMapper.selectList(queryWrapper);
        return resourceTeamConvert.toDtoList(resourceTeamList);
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public Boolean saveOrUpdate(ResourceTeamDto dto) {
        if (Objects.isNull(dto.getCmKid())) {
            ResourceTeam resourceTeam = new ResourceTeam();
            //geom
            completeGeom(resourceTeam, dto);
            resourceTeamConvert.toEntity(resourceTeam, dto);
            return this.save(resourceTeam);
        } else {
            ResourceTeam resourceTeam = baseMapper.selectById(dto.getCmKid());
            //geom
            completeGeom(resourceTeam, dto);
            resourceTeamConvert.toEntity(resourceTeam, dto);
            return this.updateById(resourceTeam);
        }
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public Boolean delete(List<Long> idList) {
        List<ResourceTeam> resourceTeamList = new ArrayList<>();
        idList.forEach(id -> {
            ResourceTeam resourceTeam = baseMapper.selectById(id);
            //判断是否还有未完成的任务
            List<InstructTeam> instructTeamList = instructTeamMapper.fetchByUsefulResourceTeam(id);
            if (CollectionUtils.isNotEmpty(instructTeamList)) {
                throw new BusinessException(String.format("应急队伍：%s，存在未完成的任务无法删除", resourceTeam.getTeamName()));
            }
            resourceTeam.setCmUsable(true);
            resourceTeamList.add(resourceTeam);
        });
        return this.updateBatchById(resourceTeamList);
    }


    /**
     * query组装
     *
     * @param queryWrapper
     * @param query
     * @return
     */
    public LambdaQueryWrapper<ResourceTeam> buildQueryWrapper(LambdaQueryWrapper<ResourceTeam> queryWrapper, ResourceTeamQuery query) {
        if (Objects.nonNull(query.getCmRegflag())) {
            queryWrapper.eq(ResourceTeam::getCmRegflag, String.valueOf(query.getCmRegflag()));
        }
        if (StringUtils.isNotEmpty(query.getTeamName())) {
            queryWrapper.like(ResourceTeam::getTeamName, query.getTeamName());
        }
        if (StringUtils.isNotEmpty(query.getManagePerson())) {
            queryWrapper.like(ResourceTeam::getManagePerson, query.getManagePerson());
        }
        if (StringUtils.isNotEmpty(query.getAddress())) {
            queryWrapper.like(ResourceTeam::getAddress, query.getAddress());
        }
        //删除标识
        queryWrapper.eq(ResourceTeam::getCmUsable, query.getCmUsable());
        //更新时间倒排
        queryWrapper.orderByDesc(ResourceTeam::getCmUptime);
        return queryWrapper;
    }

    /**
     * 基于经纬度生成Geom
     *
     * @param resourceTeam
     * @param dto
     * @return
     */
    public ResourceTeam completeGeom(ResourceTeam resourceTeam, ResourceTeamDto dto) {
        BigDecimal lgtd = dto.getLgtd();
        BigDecimal lttd = dto.getLttd();
        if (Objects.nonNull(dto.getLgtd()) && Objects.nonNull(dto.getLttd())) {
            lgtd = lgtd.setScale(6, RoundingMode.HALF_UP);
            lttd = lttd.setScale(6, RoundingMode.HALF_UP);
            String theGeom = "POINT(" + lgtd + " " + lttd + ")";
            resourceTeam.setCmGeom(theGeom);
        }
        return resourceTeam;
    }
}
